/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.aries.ui.widget.demo.slice;

import com.aries.ui.util.FindViewUtil;
import com.aries.ui.view.tab.SegmentTabLayout;
import com.aries.ui.view.tab.listener.OnTabSelectListener;
import com.aries.ui.view.tab.widget.MsgView;
import com.aries.ui.view.title.TitleBarView;
import com.aries.ui.widget.demo.ResourceTable;
import com.aries.ui.widget.demo.module.tab.EventBusAbility;
import com.aries.ui.widget.demo.module.tab.SimpleCardFragment;
import com.aries.ui.widget.demo.module.tab.SimpleFraction;
import com.aries.ui.widget.demo.module.tab.SwitchTabEvent;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSlider;
import ohos.agp.components.PageSliderProvider;
import ohos.agp.utils.Color;
import ohos.agp.window.service.WindowManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

public class SegmentTabAbilitySlice extends AbilitySlice {
    private ArrayList<Component> mFragments = new ArrayList<>();
    private ArrayList<Fraction> mFragments2 = new ArrayList<>();
    private String[] mTitles = {"首页", "消息"};
    private String[] mTitles_2 = {"首页", "消息", "联系人"};
    private String[] mTitles_3 = {"首页", "消息", "联系人", "更多"};
    private Component mDecorView;
    private SegmentTabLayout mTabLayout_3;
    private SegmentTabLayout tabLayout_4;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_segment_tab);
        EventBus.getDefault().register(this);
        initView();
        initTitleBar();
    }

    private void initTitleBar() {
        TitleBarView titleBar = (TitleBarView) findComponentById(ResourceTable.Id_titleBar);
        titleBar.setTitleMainText("SegmentTabLayout示例").setOnLeftTextClickListener(component -> terminate());
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    public void initView() {
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        for (String title : mTitles_3) {
            SimpleCardFragment simpleCardFragment = new SimpleCardFragment(getContext());
            simpleCardFragment.setTitle("Switch ViewPager "+title);
            mFragments.add(simpleCardFragment);
        }

        for (String title : mTitles_2) {
            mFragments2.add(SimpleFraction.getInstance(title));
        }

        mDecorView = findComponentById(ResourceTable.Id_scroll);

        SegmentTabLayout tabLayout_1 = FindViewUtil.getTargetView(mDecorView,ResourceTable.Id_tl_1);
        SegmentTabLayout tabLayout_2 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_2);
        mTabLayout_3 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_3);
        tabLayout_4 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_4);
        SegmentTabLayout tabLayout_5 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_tl_5);

        tabLayout_1.setTabData(mTitles);
        tabLayout_2.setTabData(mTitles_2);
        tl_3();
        if (getAbility() instanceof FractionAbility) {
            FractionAbility ability = (FractionAbility) getAbility();
            tabLayout_4.setTabData(mTitles_2, ability, ResourceTable.Id_fl_change, mFragments2);
        }
        tabLayout_5.setTabData(mTitles_3);
        //显示未读红点
        tabLayout_1.showDot(1);
        tabLayout_2.showDot(2);
        mTabLayout_3.showDot(1);
        tabLayout_4.showDot(1);
//        //设置未读消息红点
        mTabLayout_3.showDot(2);
        MsgView rtv_3_2 = mTabLayout_3.getMsgView(2);
        if (rtv_3_2 != null) {
            rtv_3_2.setBackgroundColor(Color.getIntColor("#6D8FB0"));
        }
        tabLayout_4.setCurrentTab(2);
    }

    private void tl_3() {
        final PageSlider vp_3 = FindViewUtil.getTargetView(mDecorView, ResourceTable.Id_vp_2);
        vp_3.setProvider(new MyPagerAdapter());
//        vp_3.setPageCacheSize(mTitles_3.length);
        mTabLayout_3.setTabData(mTitles_3);
        mTabLayout_3.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                vp_3.setCurrentPage(position,false);
//                系统ToastDialog不类似于Toast 会导致卡顿
//                new ToastDialog(getContext()).setText("onTabSelect:" + position).show();
            }

            @Override
            public void onTabReselect(int position) {
//                new ToastDialog(getContext()).setText( "onTabReselect:" + position).show();
            }
        });

        vp_3.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {
            }

            @Override
            public void onPageSlideStateChanged(int i) {
            }

            @Override
            public void onPageChosen(int position) {
                mTabLayout_3.setCurrentTab(position);
            }


        });
        mTabLayout_3.setCurrentTab(0);

        findComponentById(ResourceTable.Id_btn_eventTab).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                Intent intent = new Intent();
                Operation build = new Intent.OperationBuilder()
                        .withBundleName("com.aries.ui.widget.demo")
                        .withAbilityName(EventBusAbility.class)
                        .build();
                intent.setOperation(build);
                startAbility(intent);
            }
        });
    }

    private class MyPagerAdapter extends PageSliderProvider {
        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public Object createPageInContainer(ComponentContainer componentContainer, int i) {
            componentContainer.addComponent(mFragments.get(i));
            return componentContainer;
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
//            componentContainer.removeComponent((Component) o);
            componentContainer.removeComponent(mFragments.get(i));
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object o) {
            return component==o;
        }

        @Override
        public String getPageTitle(int position) {
            return mTitles_3[position];
        }
    }

    /**
     * 主要演示 刷新上一页面tab时 Fragment 不同时切换问题{@link com.aries.ui.view.tab.utils.FragmentChangeManager#setFragments(int)}
     * 原{@link FragmentTransaction#commit()}修改为{@link FragmentTransaction#commitAllowingStateLoss()}
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SwitchTabEvent event) {
        tabLayout_4.setCurrentTab(event.getPosition() == tabLayout_4.getCurrentTab() ? 1 : event.getPosition());
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
